import { AppConfig } from '@/config/config';
import { AppService } from '@/service/app-service';
import { getCookie } from '@/utils/util';
import { AxiosRequestConfig } from 'axios';
import { Http } from './http';

/**
 * 拦截器
 *
 * @export
 * @class Interceptors
 */
export class Interceptors {

    /**
     * 路由对象
     *
     * @private
     * @type {any}
     * @memberof Interceptors
     */
    private router: any;

    /**
     *  单列对象
     *
     * @private
     * @static
     * @type { Interceptors }
     * @memberof Interceptors
     */
    private static readonly instance: Interceptors = new Interceptors();

    /**
     * Creates an instance of Interceptors.
     * 私有构造，拒绝通过 new 创建对象
     * 
     * @memberof Interceptors
     */
    private constructor() {
        if (Interceptors.instance) {
            return Interceptors.instance;
        } else {
            this.intercept();
        }
    }

    /**
     * 初始化
     *
     * @static
     * @returns {Interceptors}
     * @memberof Interceptors
     */
    public static init(router: any): Interceptors {
        this.instance.router = router;
        return this.instance;
    }

    /**
     * 拦截器实现接口
     *
     * @private
     * @memberof Interceptors
     */
    private intercept(): void {
        Http.getHttp().interceptors.request.use((config: AxiosRequestConfig) => {
            const appdata = AppService.getInstance().getAppData();
            if (appdata && appdata.context) {
                config.headers['srforgsectorid'] = appdata.context.srforgsectorid;
            }
            if (AppConfig.SaaSMode) {
                let activeOrgData: any = getCookie('activeOrgData') ? JSON.parse(getCookie('activeOrgData') as string) : {};
                config.headers['srforgid'] = activeOrgData?.orgid;
                config.headers['srfsystemid'] = activeOrgData?.systemid;
            }
            if (getCookie('ibzuaa-token')) {
                config.headers['Authorization'] = `Bearer ${getCookie('ibzuaa-token')}`;
            }
            config.url = AppConfig.baseUrl + config.url;
            return config;
        }, (error: any) => {
            return Promise.reject(error);
        });

        Http.getHttp().interceptors.response.use((response: any) => {
            if (response.status === 401) {
                this.doNoLogin(response, response.data);
            }
            return response;
        }, (error: any) => {
            return Promise.reject(error);
        });
    }

    /**
     * 处理未登录异常情况
     *
     * @private
     * @param {*} [data={}]
     * @memberof Interceptors
     */
    private doNoLogin(response: any, data: any = {}): void {
        // 交由路由守卫自行处理
        if (response && response.config && response.config.url && Object.is(response.config.url, '/appdata')) {
            return;
        }
        AppService.getInstance().clearAppData();
        if (Object.is(this.router.currentRoute.name, 'login')) {
            return;
        }
        this.router.push({ name: 'Login' });
    }

}